package com.googlecode.wickedforms.xvergabe.togglestamper;

import org.xvergabe.xsd.forms.components.x20.FormMetaData;
import org.xvergabe.xsd.forms.components.x20.FormMetaData.ActivationToggle;

import com.googlecode.wickedforms.model.FormModel;
import com.googlecode.wickedforms.model.actions.ToggleEnabledAction;
import com.googlecode.wickedforms.model.elements.fields.AbstractInputFieldModel;

/**
 * This class provides methods to add Activation Toggles to a formModel.
 * Therefore you need the forms Metadata which holds all information about the
 * Activation Toggles.
 * 
 * @author schiller
 * 
 */
public class ActivationToggleStamper {

	/**
	 * reads the activation Toggles from the given FormMetaData and adds them to
	 * the corresponding fields
	 * 
	 * @param metadata
	 *            the forms Metadata which holds the Activation Toggles
	 * @param formModel
	 *            the formModel to add the Toggles to
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void stampActivationToggles(FormMetaData metadata,
			FormModel formModel) {

		for (ActivationToggle activationToggle : metadata
				.getActivationToggleArray()) {

			AbstractInputFieldModel triggerField = (AbstractInputFieldModel) formModel
					.getMainSection().getElementById(
							activationToggle.getTriggerField());
			if (triggerField == null) {
				throw new RuntimeException(String.format(
						"Trigger Field with id %s does not exist!",
						activationToggle.getTriggerField()));
			}

			AbstractInputFieldModel targetField = (AbstractInputFieldModel) formModel
					.getMainSection().getElementById(
							activationToggle.getTargetField());
			if (targetField == null) {
				throw new RuntimeException(String.format(
						"Target Field with id %s does not exist!",
						activationToggle.getTargetField()));
			}

			if (activationToggle.isSetTriggerValue()) {
				// whether it is a trigger for an explicit value
				triggerField.add(new ToggleEnabledAction(triggerField,
						activationToggle.getTriggerValue(), targetField));
			} else {
				// or there is no triggervalue given, means it is a checkbox
				triggerField.add(new ToggleEnabledAction<Boolean>(triggerField,
						Boolean.TRUE, targetField));
			}

		}

	}

}
